"""
用于管理所有连入mqtt的设备, 后续可以改为使用redis进行缓存的多节点管理
"""
from __future__ import annotations
from .dto import mqtt
from amqtt.session import Session
from typing import Dict
import uuid
import random

CONNECTIONS: Dict[str, ClientDevice] = {}

class ClientDevice:
    __slots__ = (
        "__weakref__",
        "client_id",
        "client_session",
        "session_id",
        "mac_address",
        "udp_info",
    )

    def __init__(self, client_id: str, client_session: Session):
        self.client_id = client_id
        self.client_session = client_session
        groups = client_id.split("@@@")
        if len(groups) == 3:
            assert groups[0] == "GID_test"
            # 这里是下划线而不是:
            self.mac_address = groups[1].lower()
            # username maybe
        else:
            self.mac_address = "_".join(f"{random.randint(0, 255):02X}" for _ in range(6))

    @property
    def subscribe_topic(self) -> str:
        """
        示例 devices/p2p/00_22_44_66_88_00
        """
        return f"devices/p2p/{self.mac_address}"

    def from_hello(self, hello: mqtt.HelloMessage):
        # TODO: 根据hello消息内容进行初始化
        self.session_id = str(uuid.uuid4())[:8]
        return self

    def hello_back(self) -> mqtt.HelloResponse:
        """生成Hello响应"""
        hello = mqtt.HelloResponse(
            session_id=self.session_id,
            udp=mqtt.UdpInfo(
                server="192.168.2.1",
                port=8888,
            )
        )
        self.udp_info = hello.udp
        return hello
